package com.zzu.chat.chat.detail;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;

import com.google.android.material.appbar.MaterialToolbar;
import com.zzu.chat.R;

import com.zzu.chat.bean.Blink;
import com.zzu.chat.bean.Comment;
import com.zzu.chat.chat.detail.adapter.Blink_Detail_Adapter;
import com.zzu.chat.chat.detail.adapter.Comments_Adapter;
import com.zzu.chat.util.TimeUtils;


import java.util.LinkedList;
import java.util.List;

import cn.leancloud.AVObject;
import cn.leancloud.AVQuery;
import cn.leancloud.AVUser;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

public class Chat_CommentActivity extends Activity {
    private LinkedList<Comment> comments = new LinkedList<>();
    private LinkedList<Blink> blinks = new LinkedList<>();
    private Blink blink;
    private Blink_Detail_Adapter blink_detail_adapter ;
    private Comments_Adapter comments_adapter;
    private RecyclerView recyclerview_chat_detail,recyclerview_chat_detail2;
    private MaterialToolbar materialToolbar;
    private Button button_add_comment;
    private String text,blinkId;
    private EditText et_add_comment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat__comment);
        materialToolbar = findViewById(R.id.topAppBar);
        recyclerview_chat_detail = findViewById(R.id.recyclerview_chat_detail);
        et_add_comment = findViewById(R.id.et_add_comment);
        button_add_comment = findViewById(R.id.bt_add_comment);

        addListener_for_toolbar();
        configure_blink_detail_adapter();
        addListener_addComment();
    }
    /**
    * get blinkId
    * */
    public void get_blink_id(){
        blinkId = getIntent().getStringExtra("blinkObjectId");
    }
    /**
     * get blink by objectid
    * */
    public void getBlink(){
        get_blink_id();
        /*blinkId = getIntent().getStringExtra("这里为前台传送的数据的名字param");*/
//        String blinkidd;
//        blinkId = "5fe1eeb40c43906a18d8eb2e";
        if (blinkId!=null){
            AVQuery<AVObject> query = new AVQuery<>("Blink");
            query.whereEqualTo("objectId",blinkId);
            query.findInBackground().subscribe(new Observer<List<AVObject>>() {
                public void onSubscribe(Disposable disposable) {}
                public void onNext(List<AVObject> students) {
                    for (AVObject avObject : students){
                        System.out.println("原始数据"+avObject.toString());
                        blinks.add(TimeUtils.getBlinkClass(avObject));
                        System.out.println("当前blink"+blinks.toString());
                    }

                    System.out.println("已成功抓取动态一条!!");
                    show_blink();

                }
                public void onError(Throwable throwable) {
                    System.out.println("抓取动态失败！！");
                }
                public void onComplete() {}
            });
        }


    }

    public LinkedList<Comment> getComments(){
        AVQuery<AVObject> query = new AVQuery<>("Comment");
        /*query.whereEqualTo("Blink",blink);*/
        query.orderByDescending("createdAt");
        query.whereEqualTo("blink_objectId",blinkId);
        query.findInBackground().subscribe(new Observer<List<AVObject>>() {
            public void onSubscribe(Disposable disposable) {}
            public void onNext(List<AVObject> students) {
                for (AVObject avObject : students) {
                   comments.add(TimeUtils.getCommentClass(avObject));
                }
                show_blink();
                blink_detail_adapter.set_progressbar_unvisible();
                Log.d("检查读取到的评论数量",String.valueOf(comments.size()));
            }
            public void onError(Throwable throwable) {}
            public void onComplete() {}
        });
        return comments;
    }
    /**
     * configure listener for {@link Chat_CommentActivity#materialToolbar}
     * */
    public void addListener_for_toolbar(){
        materialToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
        materialToolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()){
                    case R.id.add_comment:
                        Intent intent = new Intent(Chat_CommentActivity.this,Chat_Add_CommentActivity.class);
                        intent.putExtra("id",blinkId);
                        startActivityForResult(intent,0);

                    default:
                }
                return false;
            }
        });
    }
    /**
     * show blink
    * */
    public void show_blink(){
        blink_detail_adapter.notifyDataSetChanged();
    }
    /**/
    public void show_comment(){
        comments_adapter.notifyDataSetChanged();
    }

    public void configure_blink_detail_adapter(){
        getBlink();
        getComments();
        blink_detail_adapter = new Blink_Detail_Adapter(blinks,comments,getApplicationContext());
        recyclerview_chat_detail.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
        recyclerview_chat_detail.setAdapter(blink_detail_adapter);

    }
    @Deprecated
    /**
    //configure comments_adapter in blink_detail_adapter*/
    public void configure_comments_adapter(){
        comments_adapter = new Comments_Adapter(comments,getApplicationContext());
        getComments();
        blink_detail_adapter.set_CommentAdapter(comments_adapter);
    }
    /**
     * configure listener for {@link Chat_CommentActivity#button_add_comment}
    * */
    public void addListener_addComment(){
        button_add_comment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                text = et_add_comment.getText().toString();
                try {
                    add_comment();
                    et_add_comment.clearFocus();
                    et_add_comment.setText("");
                    InputMethodManager imm = (InputMethodManager) Chat_CommentActivity.this
                            .getSystemService(Activity.INPUT_METHOD_SERVICE);
                    if(imm.isActive()){
                        imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                    }
                }catch (Exception e){
                    Log.e("点击发布评论按钮","发布失败！！！");
                }
                /*startActivity(new Intent(Chat_Add_CommentActivity.this,Chat_CommentActivity.class));*/


            }
        });
    }
    /**
     * //add comment*/
    public void add_comment(){
        AVObject todo = new AVObject("Comment");
        AVUser avUser = AVUser.getCurrentUser();
        todo.put("username", avUser.getUsername());
        todo.put("commentContent", text);
        todo.put("blink_objectId",blinkId);
        todo.saveInBackground().subscribe(new Observer<AVObject>() {
            public void onSubscribe(Disposable disposable) {}
            public void onNext(AVObject todo) {
                // 成功保存之后，执行其他逻辑
                System.out.println("保存成功。objectId：" + todo.getObjectId());
                comments.clear();
                getComments();
            }
            public void onError(Throwable throwable) {
                // 异常处理
            }
            public void onComplete() {}
        });

    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 0){
            comments.clear();
            getComments();
        }
    }
}